package com.example.yichuangyun.ui.activity.business;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityEditBusinessBinding;
import com.example.yichuangyun.dialog.MyDialog;
import com.example.yichuangyun.dialog.SinglePickerView;
import com.example.yichuangyun.http.ApiFactory;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.FileModel;
import com.example.yichuangyun.model.business.BusinessDetailsModel;
import com.example.yichuangyun.model.business.BusinessSourceModel;
import com.example.yichuangyun.model.business.CompanyDataModel;
import com.example.yichuangyun.model.business.NewAddBusinessModel;
import com.example.yichuangyun.model.business.ProductModel;
import com.example.yichuangyun.model.contacts.ContactPersonModel;
import com.example.yichuangyun.model.contacts.ContactWayModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.ui.adapter.AddContactAdapter;
import com.example.yichuangyun.utils.CashierInputFilter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UMengUtil;
import com.example.yichuangyun.utils.pictrue.GlideEngine;
import com.example.yichuangyun.utils.producttreelist.ProductNodeModel;
import com.google.gson.Gson;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureSelectorStyle;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

/**
 * 新增商机
 */
public class EditBusinessActivity extends BaseActivity<ActivityEditBusinessBinding, BaseViewModel> implements View.OnClickListener, AddContactAdapter.OnChangeButtonStatusListener {

    private ActivityResultLauncher<Intent> launcherResult;
    private ActivityResultLauncher<Intent> requestAddProduct;
    private ActivityResultLauncher<Intent> requestAddSource;

    /**
     * 商机详情id
     */
    private String businessId;

    private SinglePickerView singlePickerView;

    /**
     * 关联企业
     */
    private final List<String> companyData = new ArrayList<>();

    /**
     * 联系人信息
     */
    private List<ContactPersonModel> contactPersonData = new ArrayList<>();
    private AddContactAdapter addContactAdapter;
    private final List<FileModel> imgList = new ArrayList<>();

    /**
     * 意向产品
     */
    private HashSet<ProductNodeModel> productData = new HashSet<>();
    private List<ProductModel> productList = new ArrayList<>();

    private final List<ProductNodeModel> mData = new ArrayList<>();
    /**
     * 商机来源id
     */
    private String sourceId;
    /**
     * 商机来源
     */
    private Set<ProductNodeModel> sourceData = new HashSet<>();
    private List<BusinessSourceModel> sourceList = new ArrayList<>();

    /**
     * 业务类型，0企业业务(已设立) 1企业业务(拟设立) 2个人业务
     */
    private int category;
    private String comName = "", creditNo;
    private String poolId;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        launcherResult = createActivityResultLauncher();
        initTitleBar(getString(R.string.new_add_business));
        companyData.add(getString(R.string.company_established));
        companyData.add(getString(R.string.company_to_be_established));
        companyData.add(getString(R.string.personal_business));
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            initTitleBar(getString(R.string.edit_business));
            businessId = bundle.getString(Constant.businessIdKey);
            creditNo = bundle.getString(Constant.creditNoKey);
            comName = bundle.getString(Constant.nameKey);
            getBusinessDetailsInfo();
        }
        binding.includeBaseInfo.ivAddInfo.setVisibility(View.GONE);
        binding.includeBaseInfo.etMoney.setFilters(new InputFilter[]{new CashierInputFilter()});
        initDialog();
        requestAddProduct = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                if (result.getData() != null) {
                    productList.clear();
                    productData = (HashSet<ProductNodeModel>) result.getData().getSerializableExtra(Constant.listKey);
                    if (productData != null) {
                        for (ProductNodeModel productNodeModel : productData) {
                            ProductModel productModel = new ProductModel(productNodeModel.getParentId(), productNodeModel.getProductid(), productNodeModel.getTitle(), productNodeModel.getType(), productNodeModel.getPoolid());
                            productList.add(productModel);
                        }
                        StringBuilder builder = new StringBuilder();
                        for (ProductNodeModel model : productData) {
                            builder.append(model.getTitle()).append("，");
                        }
                        binding.includeBaseInfo.tvProductName.setText(builder.substring(0, builder.toString().length() - 1));
                    }
                    changeBtnStatus();
                }
            }
        });
        requestAddSource = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                if (result.getData() != null) {
                    sourceList.clear();
                    sourceData = (HashSet<ProductNodeModel>) result.getData().getSerializableExtra(Constant.listKey);
                    if (sourceData != null) {
                        for (ProductNodeModel productNodeModel : sourceData) {
                            BusinessSourceModel businessSourceModel = new BusinessSourceModel(productNodeModel.getId(), productNodeModel.getTitle());
                            sourceList.add(businessSourceModel);
                        }
                        binding.tvBusinessFrom.setText(sourceList.get(0).getSource());
                    }
                    changeBtnStatus();
                }
            }
        });
    }

    /**
     * 商机详情
     */
    private void getBusinessDetailsInfo() {
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getBusinessDetails(businessId), new MyObserver<HttpRespond<BusinessDetailsModel>>() {
            @Override
            protected void onSuccess(HttpRespond<BusinessDetailsModel> businessDetailsModelHttpRespond) {
                if (Constant.SUCCESS == businessDetailsModelHttpRespond.code) {
                    BusinessDetailsModel detailsModel = businessDetailsModelHttpRespond.data;
                    if (null != detailsModel) {
                        productList = detailsModel.getProductList();
                        for (ProductModel productModel : productList) {
                            poolId = productModel.getPoolId();
                            productData.add(new ProductNodeModel(productModel.getProductName(), productModel.getId(), productModel.getParentId(), productModel.getProductId(), productModel.getPoolId(), productModel.getType(), 0, productModel.getParentProductId()));
                        }
                        StringBuilder stringBuilder = new StringBuilder();
                        for (ProductModel productModel : productList) {
                            stringBuilder.append(productModel.getProductName()).append(",");
                        }
                        binding.includeBaseInfo.tvProductName.setText(stringBuilder.substring(0, stringBuilder.toString().length() - 1));
                        binding.includeBaseInfo.etWeight.setText(CommonUtil.checkText(detailsModel.getChanceWeight()));
                        binding.includeBaseInfo.etMoney.setText(CommonUtil.checkText(detailsModel.getExpectFree()));
                        sourceList = detailsModel.getSourceLists();
                        for (BusinessSourceModel sourceModel : sourceList) {
                            sourceData.add(new ProductNodeModel(sourceModel.getSource(), sourceModel.getSourceId()));
                        }

                        if (null != sourceList && sourceList.size() > 0) {
                            binding.tvBusinessFrom.setText(CommonUtil.checkText(sourceList.get(0).getSource()));
                            sourceId = sourceList.get(0).getSourceId();
                        }
                        binding.includeBaseInfo.etNote.setText(CommonUtil.checkText(detailsModel.getRemark()));
                        category = detailsModel.getServiceCategory();
                        // 业务类型，0企业业务(已设立) 1企业业务(拟设立) 2个人业务
                        binding.includeBaseInfo.textCompanyNameText.setText(category == 0 ? getString(R.string.company_name_star) : getString(R.string.company_name));
                        binding.includeBaseInfo.tvRelationCompany.setText(category == 0 ? getString(R.string.company_established) : category == 1 ? getString(R.string.company_to_be_established) : getString(R.string.personal_business));
                        binding.includeBaseInfo.llCompanyName.setVisibility(category == 2 ? View.GONE : View.VISIBLE);
                        binding.includeBaseInfo.etCompanyName.setText(CommonUtil.checkText(detailsModel.getCompName()));
                        contactPersonData = detailsModel.getAppTels();
                        addContactAdapter.onRefresh(contactPersonData);
                        changeBtnStatus();
                        getBusinessSource();
                    }
                }
            }
        });
    }

    private void getBusinessSource() {
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getBusinessSource(""), new MyObserver<HttpRespond<List<ProductNodeModel>>>() {
            @Override
            protected void onSuccess(HttpRespond<List<ProductNodeModel>> listHttpRespond) {
                if (Constant.SUCCESS == listHttpRespond.code) {
                    if (listHttpRespond.data != null) {
                        for (int i = 0; i < listHttpRespond.data.size(); i++) {
                            ProductNodeModel node = listHttpRespond.data.get(i);
                            mData.add(new ProductNodeModel(node.getLabel(), node.getId(), node.getParentId(), node.getUseState()));
                            initList(listHttpRespond.data.get(i).getChildren());
                        }

                        int useState = 0;
                        for (ProductNodeModel m : mData) {
                            if (m.getId().equals(sourceId)) {
                                useState = m.getUseState();
                                break;
                            }
                        }
                        binding.rlBusinessFrom.setEnabled(useState != 1);
                        binding.tvBusinessFrom.setTextColor(useState == 1 ? 0xFF999999 : 0xFF3B3A40);
                    }
                }
            }
        });
    }

    private void initList(List<ProductNodeModel> list) {
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                ProductNodeModel node = list.get(i);
                mData.add(new ProductNodeModel(node.getLabel(), node.getId(), node.getParentId(), node.getUseState()));
                initList(node.getChildren());
            }
        }
    }

    private void initDialog() {
        singlePickerView = new SinglePickerView(this, getString(R.string.work_type), companyData) {
            @Override
            public void confirm(String label, int position) {
                int mCategory = label.equals(getString(R.string.company_established)) ? 0 : label.equals(getString(R.string.company_to_be_established)) ? 1 : 2;
                if (category != mCategory) {
                    category = mCategory;
                    binding.includeBaseInfo.llCompanyName.setVisibility(category == 2 ? View.GONE : View.VISIBLE);
                    binding.includeBaseInfo.textCompanyNameText.setText(category == 0 ? getString(R.string.company_name_star) : getString(R.string.company_name));
                    binding.includeBaseInfo.tvRelationCompany.setText(label);
                    binding.includeBaseInfo.etCompanyName.setText("");
                    binding.includeBaseInfo.tvProductName.setText("");
                    productData.clear();
                    changeBtnStatus();
                }
            }
        };
    }

    @Override
    public void initCtrl() {
        addContactAdapter = new AddContactAdapter(context, contactPersonData, this, true);
        binding.contactRecyclerView.setAdapter(addContactAdapter);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initClick() {
        binding.includeBaseInfo.rlAddProduct.setOnClickListener(this);
        binding.rlBusinessFrom.setOnClickListener(this);
        binding.rlUploadImg.setOnClickListener(this);
        binding.ivDelete.setOnClickListener(this);
        binding.includeBaseInfo.rlRelationCompany.setOnClickListener(this);
        binding.btnConfirm.setOnClickListener(this);
        binding.includeBaseInfo.etCompanyName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!comName.equals(binding.includeBaseInfo.etCompanyName.getText().toString())) {
                    Log.e("@@@@@@@", "111111" + creditNo);
                    creditNo = null;
                }
                changeBtnStatus();
            }
        });
        binding.includeBaseInfo.etCompanyName.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //关闭软键盘
                CommonUtil.closeKeyboard(EditBusinessActivity.this);
                creditNo = null;
                getInfoByCompanyName();
                changeBtnStatus();
                return true;
            }
            return false;
        });
        binding.includeBaseInfo.etWeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().startsWith("0")) {
                    editable.clear();
                }
                changeBtnStatus();
            }
        });
    }

    /**
     * 根据企业名称模糊查询信息
     */
    private void getInfoByCompanyName() {
        String companyName = binding.includeBaseInfo.etCompanyName.getText().toString();
        Map<String, Object> map = new HashMap<>();
        map.put("keyword", companyName);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(map));
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getCompanyByQxb(requestBody), new MyObserver<HttpRespond<CompanyDataModel>>() {
            @Override
            protected void onSuccess(HttpRespond<CompanyDataModel> companyDataModelHttpRespond) {
                if (Constant.SUCCESS == companyDataModelHttpRespond.code) {
                    if (null != companyDataModelHttpRespond.data) {
                        List<CompanyDataModel.CompanyInfoModel> list = companyDataModelHttpRespond.data.getItems();
                        if (null != list && list.size() > 0) {
                            List<String> mComList = new ArrayList<>();
                            for (CompanyDataModel.CompanyInfoModel comModel : list) {
                                mComList.add(comModel.getName() /*+ "\n" + comModel.getCreditNo()*/);
                            }
                            CommonUtil.closeKeyboard(EditBusinessActivity.this);
                            SinglePickerView singlePickerView = new SinglePickerView(EditBusinessActivity.this, getString(R.string.choose_company), mComList) {
                                @Override
                                public void confirm(String label, int position) {
                                    comName = list.get(position).getName();
                                    creditNo = list.get(position).getCreditNo();
                                    binding.includeBaseInfo.etCompanyName.setText(list.get(position).getName());
                                    changeBtnStatus();
                                }
                            };
                            singlePickerView.showSinglePickerView();
                        } else {
                            creditNo = null;
                        }
                    }
                } else {
                    ToastHelper.show(companyDataModelHttpRespond.msg);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        CommonUtil.closeKeyboard(this);
        int id = v.getId();// 意向产品
        if (id == R.id.rl_add_product) {
            if (CommonUtil.isCanClick()) {
                Intent intent = new Intent(EditBusinessActivity.this, ProductActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(Constant.poolIdKey, poolId);
                bundle.putInt(Constant.categoryKey, binding.includeBaseInfo.tvRelationCompany.getText().toString().equals(context.getString(R.string.personal_business)) ? 2 : 1);
                bundle.putSerializable(Constant.listKey, productData);
                bundle.putBoolean(Constant.isEditProductKey, true);
                intent.putExtras(bundle);
                requestAddProduct.launch(intent);
            }
            // 商机来源
        } else if (id == R.id.rl_business_from) {
            Intent intent = new Intent(EditBusinessActivity.this, ProductActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.flagKey, 1);
            bundle.putSerializable(Constant.listKey, (Serializable) sourceData);
            intent.putExtras(bundle);
            requestAddSource.launch(intent);
        } else if (id == R.id.rl_upload_img) {
            PictureSelector.create(context).openGallery(SelectMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .setImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                    .setSelectorUIStyle(new PictureSelectorStyle()).setCameraImageFormat(PictureMimeType.PNG) // 拍照保存图片格式后缀,默认jpeg,Android Q使用PictureMimeType.PNG_Q
                    .setSelectionMode(SelectModeConfig.SINGLE) // 单选
                    .setCompressEngine((CompressFileEngine) (context, source, call) -> Luban.with(context).load(source).ignoreBy(100).setCompressListener(new OnNewCompressListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onSuccess(String source, File compressFile) {
                            if (call != null) {
                                call.onCallback(source, compressFile.getAbsolutePath());
                            }
                        }

                        @Override
                        public void onError(String source, Throwable e) {
                            if (call != null) {
                                call.onCallback(source, null);
                            }
                        }
                    }).launch()).forResult(launcherResult);
        } else if (id == R.id.rl_relation_company) {
            singlePickerView.showSinglePickerView();
        } else if (id == R.id.iv_delete) {
            binding.rlImgInfo.setVisibility(View.GONE);
            imgList.clear();
        } else if (id == R.id.btn_confirm) {
            if (category == 0 && TextUtils.isEmpty(creditNo)) {
                binding.includeBaseInfo.etCompanyName.setText("");
                ToastHelper.show(getString(R.string.input_company_name));
                return;
            }
            save(0);
        }
    }

    /**
     * 修改商机
     */
    private void save(int replaceCompanyType) {
        UMengUtil.setCountEventId(Constant.SAVE_EDIT_BUSINESS);
        showLoadingDialog();
        NewAddBusinessModel newAddBusinessModel = new NewAddBusinessModel();
        newAddBusinessModel.setId(businessId);
        newAddBusinessModel.setReplaceCompanyType(replaceCompanyType);
        newAddBusinessModel.setChanceWeight(binding.includeBaseInfo.etWeight.getText().toString());
        newAddBusinessModel.setExpectFree(binding.includeBaseInfo.etMoney.getText().toString());
        newAddBusinessModel.setRemark(binding.includeBaseInfo.etNote.getText().toString());
        newAddBusinessModel.setServiceCategory(category);
        newAddBusinessModel.setCompName(binding.includeBaseInfo.etCompanyName.getText().toString());
        newAddBusinessModel.setCreditNo(creditNo);
        newAddBusinessModel.setPros(productList);
        newAddBusinessModel.setSourceLists(sourceList);
        newAddBusinessModel.setAppTels(contactPersonData);
        newAddBusinessModel.setClueRecordRefs(imgList);
        Log.e("@修改商机入参：", new Gson().toJson(newAddBusinessModel));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(newAddBusinessModel));
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().editBusinessDetail(requestBody), new MyObserver<HttpRespond<String>>() {
            @Override
            protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                if (stringHttpRespond.code == Constant.SUCCESS) {
                    ToastHelper.show("修改商机成功");
                    EventBus.getDefault().post(new EventBusModel(Constant.refreshInformationDetail));
                    EventBus.getDefault().post(new EventBusModel(Constant.refreshMainBusinessList));
                    EditBusinessActivity.this.finish();
                } else if (stringHttpRespond.code == 10001) {
                    MyDialog myDialog = new MyDialog(EditBusinessActivity.this) {
                        @Override
                        public void rightClick() {
                            save(1);
                        }
                    };
                    myDialog.setText(getString(R.string.tips), getString(R.string.transfer_tips), getString(R.string.cancel), getString(R.string.confirm_transfer));
                    myDialog.showDialog();
                } else {
                    ToastHelper.show(stringHttpRespond.msg);
                }
                dismissLoadingDialog();
            }

            @Override
            protected void onFail(Throwable e) {
                super.onFail(e);
                ToastHelper.show(e.getMessage());
                dismissLoadingDialog();
            }
        });
    }

    /**
     * 上传图片
     */
    private void uploadImg(File file) {
        showLoadingDialog();
        MultipartBody.Part part = null;
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        try {
            // 路径有中文名要进行编码
            part = MultipartBody.Part.createFormData("file", URLEncoder.encode(file.getName(), "utf-8"), requestBody);
            RetrofitHelper.getInstance().execute(RetrofitHelper.getService().uploadImage(part), new MyObserver<HttpRespond<String>>() {
                @Override
                protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                    if (Constant.SUCCESS == stringHttpRespond.code) {
                        if (!TextUtils.isEmpty(stringHttpRespond.data)) {
                            imgList.clear();
                            imgList.add(new FileModel(file.getName(), ApiFactory.IMAGE_UPLOAD + stringHttpRespond.data, 1));
                            binding.rlImgInfo.setVisibility(View.VISIBLE);
                            binding.tvImgName.setText(file.getName());
                        } else {
                            ToastHelper.show(stringHttpRespond.msg);
                        }
                    }
                    dismissLoadingDialog();
                }

                @Override
                protected void onFail(Throwable e) {
                    dismissLoadingDialog();
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private void changeBtnStatus() {
//        Log.e("@@@@@@changeBtnStatus", contactPersonData.size()+"==");
        boolean isALlContact = true;
        for (int i = 0; i < contactPersonData.size(); i++) {
            if (TextUtils.isEmpty(contactPersonData.get(i).getName()) || contactPersonData.get(i).getSex() == -1) {
                isALlContact = false;
            }
            for (int j = 0; j < contactPersonData.get(i).getTels().size(); j++) {
                ContactWayModel contactWayModel = contactPersonData.get(i).getTels().get(j);
                if (TextUtils.isEmpty(contactWayModel.getInfo())) {
                    isALlContact = false;
                } else {
                    if (contactWayModel.getType() == 1) {
                        if (contactWayModel.getInfo().length() < 11 || !contactWayModel.getInfo().startsWith("1")) {
                            isALlContact = false;
                        }
                    }
                    if (contactWayModel.getType() == 4 && !CommonUtil.isEmail(contactWayModel.getInfo())) {
                        isALlContact = false;
                    }
                }
            }
        }

        if (!TextUtils.isEmpty(binding.includeBaseInfo.tvProductName.getText().toString()) && !TextUtils.isEmpty(binding.tvBusinessFrom.getText().toString()) && !TextUtils.isEmpty(binding.includeBaseInfo.tvRelationCompany.getText().toString()) && !TextUtils.isEmpty(binding.includeBaseInfo.etWeight.getText().toString()) && isALlContact) {
            if (category == 0) {
                if (!TextUtils.isEmpty(binding.includeBaseInfo.etCompanyName.getText().toString())) {
                    binding.btnConfirm.setEnabled(true);
                    binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_sel);
                } else {
                    binding.btnConfirm.setEnabled(false);
                    binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_def);
                }
            } else {
                binding.btnConfirm.setEnabled(true);
                binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_sel);
            }
        } else {
            binding.btnConfirm.setEnabled(false);
            binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_def);
        }
    }

    @Override
    public void onChangeListener(List<ContactPersonModel> list) {
        this.contactPersonData = list;
        changeBtnStatus();
    }

    /**
     * 创建一个ActivityResultLauncher
     */
    private ActivityResultLauncher<Intent> createActivityResultLauncher() {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            int resultCode = result.getResultCode();
            if (resultCode == RESULT_OK) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(result.getData());
                for (int i = 0; i < selectList.size(); i++) {
                    LocalMedia media = selectList.get(i);
                    File file = new File(media.getCompressPath() == null ? media.getRealPath() : media.getCompressPath());
                    uploadImg(file);
                }
            }
        });
    }
}